package org.chen.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.chen.domain.Article;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Mapper
@Repository
public interface ArticleRepository extends BaseMapper<Article> {
    
    /**
     * 根据来源查询文章
     */
    @Select("SELECT * FROM video_article WHERE source = #{source} ORDER BY create_time DESC")
    List<Article> findBySource(@Param("source") String source);
    
    /**
     * 根据时间范围查询文章
     */
    @Select("SELECT * FROM video_article WHERE create_time BETWEEN #{startTime} AND #{endTime} ORDER BY create_time DESC")
    List<Article> findByCreateTimeBetween(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);
    
    /**
     * 根据URL查询文章，用于去重
     */
    @Select("SELECT * FROM video_article WHERE url = #{url} LIMIT 1")
    Article findByUrl(@Param("url") String url);
    
    /**
     * 统计各来源的文章数量
     */
    @Select("SELECT source, COUNT(*) as count FROM video_article GROUP BY source")
    List<Map<String, Object>> groupBySource();

    default Map<String, Long> countBySource() {
        return groupBySource().stream()
                .collect(Collectors.toMap(
                        m -> (String) m.get("source"),
                        m -> ((Number) m.get("count")).longValue()
                ));
    }
}